﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NCT.MRS.DataAccessLayer.Configurations;
using NCT.MRS.DataAccessLayer.Entities;

namespace NCT.MRS.DataAccessLayer
{
    public class AppContext : DbContext, IDbContext, IAppContext, IDisposable
    {
        public AppContext()
            :base("mrs_conn")
        {

        }

        public DbSet<User> Users { get; set; }
        public DbSet<Client> Clients { get; set; }
        public DbSet<Doctor> Doctors { get; set; }
        public DbSet<TestType> TestTypes { get; set; }
        public DbSet<TestPackage> TestPackages { get; set; }
        public DbSet<TestTypeSection> TestTypeSections { get; set; }
        public DbSet<TestRequest> TestRequests { get; set; }
        public DbSet<TestTypeResult> TestTypeResults { get; set; }
        public DbSet<AccessType> AccessTypes { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<AccessSection> AccessSections { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add<User>(new UserConfiguration());
            modelBuilder.Configurations.Add<Client>(new ClientConfiguration());
            modelBuilder.Configurations.Add<Doctor>(new DoctorConfiguration());
            modelBuilder.Configurations.Add<TestTypeSection>(new TestTypeSectionConfiguration());
            modelBuilder.Configurations.Add<TestPackage>(new TestPackageConfiguration());
            modelBuilder.Configurations.Add<TestRequest>(new TestRequestConfiguration());
            modelBuilder.Configurations.Add<TestType>(new TestTypeConfiguration());
            modelBuilder.Configurations.Add<TestTypeResult>(new TestTypeResultConfiguration());
            modelBuilder.Configurations.Add<AccessType>(new AccessTypeConfiguration());
            modelBuilder.Configurations.Add<Role>(new RoleConfiguration());
            modelBuilder.Configurations.Add<AccessSection>(new AccessSectionConfiguration());
            base.OnModelCreating(modelBuilder);
        }

        public override int SaveChanges()
        {
            try
            {
                return base.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                throw ex;
            }
            catch (DbUpdateException exx)
            {
                throw exx;
            }
        }

        public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
        {
            return base.Set<TEntity>();
        }

        public IEnumerable<DbEntityValidationResult> GetValidationResult()
        {
            return GetValidationErrors();
        }
    }
}
